package com.jtext.reader.jtextreader.controller;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import static com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolver.iterator;

/**
 * @author Mingjie.Li
 * @since 2019/7/9
 */
@RestController
public class FileAPIController {
    final static String fileName = "E:\\staging-cpp1\\cpp1-0604\\staging-platform2-cpp1_CPP-20190604-1.log";

    @GetMapping("/total")
    public Map<String, String> total(){
        Map<String, String> result = new HashMap<>();
        result.put("fileName", fileName);
        try {
            result.put("total", Files.lines(Paths.get(fileName)).count()+"");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    @GetMapping("search")
    public Map<String, Object> search(String keyword, int total) throws IOException {
        int firstIndex = searchFirst( keyword);
        int startIndex = (firstIndex - 1000)>0 ?  (firstIndex - 1000) : 0;
        int endIndex = (firstIndex + 1000)<total ?  (firstIndex + 1000) : total;
        List<String> contents = Files.lines(Paths.get(fileName)).limit(endIndex).skip(startIndex).collect(Collectors.toList());

        Map<String, Object> result = new HashMap<>();
        result.put("startIndex", startIndex);
        result.put("endIndex", endIndex);
        result.put("contents", contents);
        return result;
    }

    private int searchFirst(String keyword) throws IOException {
        Iterator<String> iterator = Files.lines(Paths.get(fileName)).iterator();
        int i= 0;
        while (iterator.hasNext()){
            if(iterator.next().contains(keyword)){
                return i;
            }
            i++;
        }
        return -1;
    }
}
